#!/usr/bin/env python3
"""
MD2DocKit 应用启动脚本
"""

import os
import sys
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from md2dockit.app import create_app, get_socketio
from md2dockit.app.config import config


def create_application():
    """创建Flask应用实例"""
    config_name = os.environ.get('FLASK_ENV', 'development')
    app = create_app(config[config_name])
    return app


# 创建应用实例
app = create_application()
socketio = get_socketio()


@app.cli.command()
def init_db():
    """初始化数据库"""
    from md2dockit.app.models import init_database
    init_database()
    print("数据库初始化完成")


@app.cli.command()
def create_indexes():
    """创建数据库索引"""
    from md2dockit.app.models import create_indexes
    create_indexes()
    print("数据库索引创建完成")


@app.cli.command()
def cleanup_files():
    """清理过期文件"""
    from md2dockit.app.tasks import cleanup_files
    result = cleanup_files.delay()
    print(f"文件清理任务已启动: {result.id}")


if __name__ == '__main__':
    # 开发环境直接运行
    if app.config['DEBUG']:
        socketio.run(
            app,
            host=app.config['HOST'],
            port=app.config['PORT'],
            debug=True,
            use_reloader=True
        )
    else:
        # 生产环境使用Gunicorn
        print("生产环境请使用 Gunicorn 启动应用")
        print("示例: gunicorn --worker-class eventlet -w 1 --bind 0.0.0.0:5000 run:app")